package com.han.util;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.exception.excel.ExcelImportException;
import com.google.common.collect.Lists;
import org.apache.poi.poifs.filesystem.FileMagic;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author 吴郑晗
 * @description excel 工具类
 * @date 2021年11月19日 下午5:18
 */
public class ExcelUtil {

    /**
     * excel 文件路径
     */
    public static String PATH = System.getProperty("user.dir") + File.separator + "file/";

    static {
        // 初始化路径
        File file = new File(PATH);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    /**
     * 导出excel模板不生产文件的方式
     *
     * @param fileName 文件名
     * @param response response
     * @param cls      头行注解类
     * @return
     */
    public static boolean downloadExcel(String fileName, HttpServletResponse response, Class cls, List excelVoArrayList) {
        boolean result = true;
        Workbook sheets = null;
        try (OutputStream outputStream = new BufferedOutputStream(response.getOutputStream())
        ) {
            // 创建实体对象
            ExportParams exportParams = new ExportParams();
            sheets = ExcelExportUtil.exportExcel(exportParams, cls, excelVoArrayList);
            sheets.getActiveSheetIndex();
            response.reset();
            // 设置response的Header
            response.setContentType("application/force-download");
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + new String((fileName).getBytes(), StandardCharsets.ISO_8859_1));
            sheets.write(outputStream);
            sheets.close();
        } catch (Exception e) {
//			log.error("下载excel异常：", e);
            result = false;
        } finally {
            try {
                if (sheets != null) {
                    sheets.close();
                }
            } catch (Exception e) {
//				log.error("excel页关闭异常：", e);
            }

        }
        return result;
    }

    public static <T> List<T> importExcel(MultipartFile file, Class<T> pojoClass,
                                          ImportParams params) throws Exception {
        checkExcel(file);
        return importExcel(file.getInputStream(), pojoClass, params);
    }

    public static <T> List<T> importExcel(InputStream inputstream, Class<T> pojoClass,
                                          ImportParams params) throws Exception {
        List<T> objects = ExcelImportUtil.importExcel(inputstream, pojoClass, params);
        if (objects == null || objects.isEmpty()) {
            throw new ExcelImportException(" excel中数据为空 ");
        }
        return objects;
    }

    public static boolean checkExcel(MultipartFile file) throws IOException {

        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        boolean contains = Lists.newArrayList("xls", "xlsx").contains(extension);
        if (!contains){
            throw new ExcelImportException(" 文件格式不对[只接收xls、xlsx]，而上传的文件格式却是 " + extension);
        }

        InputStream is = new BufferedInputStream(file.getInputStream());
        // 不能单独判断内存 ，因为字段标题也是占了内存的
        if(is.available() == 0){
            throw new ExcelImportException("不支持空文件导入");
        }
        int fileSize = is.available()/ 1024 /1024;
        if(fileSize > 20){
            throw new ExcelImportException("excel过大，excel文件最多20MB ，当前文件大小 "+fileSize+"MB");
        }
        FileMagic other = FileMagic.valueOf(is);
        if(FileMagic.OLE2.equals(other)){
            // 这是xls文件
        }
        if(FileMagic.OOXML.equals(FileMagic.valueOf(is))){
            // 这是xlsx文件
        }
        if(FileMagic.UNKNOWN.equals(other)){
            throw new ExcelImportException("不是excel文件");
        }
        return contains;
    }

}
